<template>
  <!-- 批量导入对话框 -->
  <a-modal
    v-model:visible="visible"
    :title="props.title"
    width="560px"
    title-align="start"
    align-center
    render-to-body
    :mask-closable="false"
    class="common-file-upload-dialog"
    @close="closed"
  >
    <div class="secret-level-ara">
      <a-form
        ref="secretFormRef"
        label-align="left"
        :model="secretForm"
        style="margin-top: 20px"
      >
        <a-form-item
          :label="'数据密级'"
          field="secretLevel"
          :rules="[{ required: true, message: '请选择' }]"
          :validate-trigger="['change']"
          style="width: 70%"
        >
          <secret-level-select
            v-model="secretForm.secretLevel"
            :default-value="secretForm.secretLevel"
            :secret-level="secretLevel"
            style="width: 100%"
          />
        </a-form-item>
      </a-form>
    </div>
    <div class="tabsone">
      <a-upload
        v-model:file-list="fileList"
        draggable
        action="/"
        :headers="upload.headers"
        :auto-upload="false"
        :accept="accept"
        :show-file-list="true"
        :default-file-list="defaultFileList"
        :limit="limitComputed"
        @before-upload="beforeUpload"
        @change="handleChange"
      >
        <template #upload-button>
          <div v-if="fileList.length === 0" class="upload-ara">
            <img
              :src="uploading"
              style="width: 48px; height: 48px; margin-bottom: 8px"
              alt=""
            />
            <div class="file-name">
              {{ '单击或拖动文件到此区域上传' }}
            </div>
            <span style="color: #828b9b">{{
              `支持${props.accept}文件格式，文件大小不超过${props.maxSize}M`
            }}</span>
          </div>
          <div v-else class="upload-ara">
            <xlsIcon style="width: 48px; height: 48px; margin-bottom: 8px" />
            <template v-if="!multiple">
              <div v-for="item in fileList" :key="item.id" class="file-name">
                {{ item.name }}
              </div>
              <a-button>重新上传</a-button>
            </template>
            <template v-else>
              <div class="file-name">
                {{ fileList[fileList.length - 1].name }}
              </div>
              <a-button>继续上传</a-button>
            </template>
          </div>
        </template>
      </a-upload>
    </div>

    <template #footer>
      <a-button @click="closed">{{ '取消' }}</a-button>
      <a-button
        v-if="!multiple"
        type="primary"
        :disabled="fileList.length === 0"
        :loading="importLoading"
        @click="importData()"
        >{{ '开始上传' }}</a-button
      >
      <a-button
        v-if="multiple"
        type="primary"
        :disabled="fileList.length === 0"
        :loading="importLoading"
        @click="importMultipleData()"
        >{{ '开始上传' }}</a-button
      >
    </template>
  </a-modal>
</template>

<script setup lang="ts">
  import { FileItem, Message } from '@arco-design/web-vue';
  import { uploadFile } from '@/api/file';
  import { getToken } from '@/utils/auth';
  import { ref, defineProps, onMounted, defineEmits, computed } from 'vue';
  import xlsIcon from '@/assets/importModel/xls.svg?component';
  import uploading from '@/common/components/image/uploading.png';
  import secretLevelSelect from '@/common/components/cac-components/secret-level-select/index.vue';

  const emit = defineEmits(['closeDrawer', 'finish', 'update:modelValue']);
  const props = defineProps({
    modelValue: {
      type: Object,
      default: null,
    },
    title: {
      type: String,
      default: '',
    },
    accept: {
      type: String,
      default: '.xlsx, .xls, .txt',
      required: false,
    },
    maxSize: {
      type: Number,
      default: 10,
    },
    limit: {
      type: Number,
      default: 5,
    },
    // 多选
    multiple: {
      type: Boolean,
      default: false,
    },
    // 默认列表 为什么不显示列表
    defaultFileList: {
      type: Array,
      default: () => [],
    },
    secretLevel: { type: Number || String, default: undefined },
  });
  const importLoading = ref<boolean>(false);

  const stepActive = ref<number>(1);
  const visible = ref(true);
  const secretFormRef = ref();
  const secretForm = ref({
    secretLevel: '',
  });

  const fileList = ref<any[]>([]);
  const upload = ref({
    // 是否禁用上传
    isUploading: false,
    // 设置上传的请求头部
    headers: {
      Authorization: `Bearer ${getToken()}`,
    },
  });
  onMounted(() => {});
  const beforeUpload = (file: any) => {
    const maxSize = props.maxSize * 1024 * 1024; // 设置最大文件大小为10MB
    return new Promise((resolve, reject) => {
      if (file.size > maxSize) {
        Message.error(`文件大小不能超过${props.maxSize}M！`);
        reject();
      }
      resolve(true);
    });
  };
  const closed = () => {
    fileList.value = [];
    emit('closeDrawer');
  };
  const importData = async () => {
    const result = await secretFormRef.value.validate();
    if (result) {
      return;
    }
    stepActive.value = 2;
    importLoading.value = true;
    const formData = new FormData();
    formData.append('file', fileList.value[0].file); // file文件
    const { name } = fileList.value[0];
    try {
      const res: any = await uploadFile(formData, {
        secretLevel: secretForm.value.secretLevel,
        path: name,
      });
      if (res.code === 200) {
        // Message.success(`文件${name}上传成功`);
        const fileParam = {
          name,
          url: res.data,
        };
        emit('update:modelValue', fileParam);
        emit('finish', fileParam);
      }
    } catch {
      // empty
    }
  };
  const importMultipleData = async () => {
    const result = await secretFormRef.value.validate();
    if (result) {
      return;
    }
    stepActive.value = 2;
    importLoading.value = true;
    const fileParam = [];
    // eslint-disable-next-line no-plusplus
    for (let index = 0; index < fileList.value.length; index++) {
      const file = fileList.value[index];
      const formData = new FormData();
      formData.append('file', file.file); // file文件
      const { name } = file;
      // eslint-disable-next-line no-await-in-loop
      const res: any = await uploadFile(formData, {
        secretLevel: secretForm.value.secretLevel,
        path: `${new Date().getTime()}${name}`,
      });
      if (res.code === 200) {
        fileParam.push({
          name,
          url: res.data,
        });
      }
    }
    emit('update:modelValue', [...props.defaultFileList, ...fileParam]);
    emit('finish', [...props.defaultFileList, ...fileParam]);
  };
  const limitComputed = computed(() => {
    if (!props.multiple) {
      return props.limit;
    }
    return props.limit - props.defaultFileList.length;
  });
  const handleChange = (fileList1: FileItem[]) => {
    if (props.multiple) {
      fileList.value = fileList1;
      return;
    }
    if (fileList1.length > 1) {
      fileList.value = fileList1.splice(1, 1);
    } else {
      fileList.value = fileList1;
    }
  };
</script>

<style lang="less">
  .common-file-upload-dialog {
    .arco-modal-header {
      padding: 12px 24px 4px;
      color: #1e2228;
    }

    .arco-modal-body {
      padding: 24px !important;
      .secret-level-ara {
        margin-bottom: 20px;
        padding: 16px 20px;
        background: #f7f9fc;
        border-radius: 6px;

        .arco-form {
          margin-top: 0 !important;

          .arco-row {
            display: flex;
            flex-direction: column;
            margin-bottom: 4px;

            .arco-form-item-label-col {
              width: 50% !important;
            }

            .arco-select-view-single {
              background-color: #fff !important;
              border: 1px solid #cad0db;
              border-radius: 4px;
            }
          }
        }
      }
      .tabsone {
        .upload-ara {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          padding: 24px 0;
          background: #f7f9fc;
          border: 1px dashed #cad0db;
          border-radius: 6px;

          .file-name {
            text-align: center;
            margin-bottom: 8px;
            font-size: 16px;
            line-height: 24px;
          }

          .upload-tip {
            height: 22px;
            margin-top: 8px;
            color: #828b9b;
            line-height: 22px;
            text-align: center;
          }
        }
        .arco-upload-list {
          .arco-upload-progress {
            display: none;
          }
        }
      }
    }

    .arco-modal-footer {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      height: 52px;
      padding: 0 24px !important;
      border-top: 1px solid #e4e7ed;
      box-shadow: none !important;
    }
  }
</style>
